//
//  HYLUserAccount.swift
//  iOSwechat
//
//  Created by apple on 16/2/28.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class HYLUserAccount: NSObject , NSCoding {

    
    
    //用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    
    // access_token的生命周期，单位是秒数。
    // 在Swift中如果是基本数据类型定义数据可选，在kvc会找不到这个key
    var expires_in: NSTimeInterval = 0 {
        didSet {
            // 当别人给expires_in属性赋值时,我们将这个expires_in转成expiresDate,方便比较时间
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    // 过期时间
    var expiresDate : NSDate?
    
    // 当前授权用户的UID。
    var uid: String?
    
    // 用户的昵称
    var screen_name: String?
    
    // 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    
    
    init(dict:[String:AnyObject]) {
        
        super.init()
        // 只有在 super.init() 后，对象才能创建完毕，才能调用对象
        self.setValuesForKeysWithDictionary(dict)
        
    }
    
    // 字典中key 模型中找不到某个属性是可以用使用这个方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print("forUndefinedKey \(key)")
    }
    
    
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate,forKey: "expiresDate")
        aCoder.encodeObject(screen_name , forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey:  "avatar_large")
    }
    
    // 解档
    required init?(coder aDecoder: NSCoder) {
       access_token = aDecoder.decodeObjectForKey("access_token") as? String
       expires_in = aDecoder.decodeDoubleForKey("expires_in")
       uid = aDecoder.decodeObjectForKey("uid") as? String
       expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
       screen_name = (aDecoder.decodeObjectForKey("screen_name") as? String)
       avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    override var description: String{
        let key = ["access_token","expires_in","uid","expiresDate","screen_name","avatar_large"];
        return "UserAccount模型: \(dictionaryWithValuesForKeys(key).description)"
    }
    
}
